import { Component, ReactNode } from 'react'
import { defaultProps, defaultState } from '../types/baseType'

type Props = defaultProps & {
	fallback: ReactNode
	children: ReactNode
}

type State = defaultState & {
	hasError: boolean
	error: Error | null
}
export default class ErrorBoundary extends Component<Props, State> {
	state = {
		hasError: false,
		error: null,
	}

	static getDerivedStateFromError(error: Error) {
		console.log('error', error)
		return {
			hasError: true,
			error,
		}
	}

	render() {
		if (this.state.hasError) {
			return this.props.fallback
		}

		return this.props.children
	}
}
